<?php
/*
 * Copyright (c) 2021.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace app\controller\adminapi\platform;

use app\common\model\platform\Platform;
use app\common\model\platform\PlatformAddon as PlatformAddonModel;
use app\common\model\platform\PlatformApp;
use app\common\model\platform\PlatformAppUser;
use app\common\model\user\UserPermission;
use app\common\model\wework\WeworkApps;
use FormBuilder\Driver\CustomComponent;
use FormBuilder\Driver\FormComponent;
use hiduoke\services\CloudServer;
use hiduoke\services\FormBuilder as Form;
use think\App;
use think\facade\Cache;

class PlatformAddon extends PlatformController
{
    /**
     * @var PlatformAddonModel
     */
    protected  $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new PlatformAddonModel();
    }

    /**
     * 平台下的平台应用列表
     */
    public function index()
    {
        // TODO 这里管理员如果卸载了应用需要重新判断一下
        $user = get_user();
        $platform = Platform::where(['plaid' => get_plaid()])->find();
        if (!$platform) {
            return $this->error("平台有误");
        }
        $where = [];
        if (!$user['is_admin'] && $platform['uid'] != $user['uid']) {
            $addon_names = (new UserPermission())->getAddonNames($user['uid'], $platform['plaid']);
            $where = [['addon_name', 'in', $addon_names]];
        }
        $data = $this->model->dkWhere($where)->getPageListModel()->append(['addon'])->withSearch(['addon'])->select();
        $count = $this->model->dkWhere($where)->getPageListModel([], false)->append(['addon'])->withSearch(['addon'])->count();
        return $this->success($count, $data);
    }

    /**
     * 应用下的平台应用列表
     * @return \think\response\Json
     */
    public function getPlatFormAddonListByAddon()
    {
        $res = $this->model->getPageList();
        return $this->success($res['count'], $res['data']->append(['platform']));
    }

    public function getListForCustomerIndex()
    {
        $data = $this->model->getPageListModel()->select()->append(['addon'])->withSearch(['addon']);
        $count = $this->model->getPageListModel([], false)->count();
        return $this->success($count, $data);
    }

    /**
     * 添加平台应用
     * @param $aid
     * @param $plaid
     */
    public function addPlatformAddon($aid, $addon_name, $plaid)
    {
        $platform_addon = $this->model->where(['addon_name' => $addon_name, 'plaid' => $plaid])->findOrEmpty();
        if (!$platform_addon->isEmpty()) {
            return $this->error('当前应用已添加');
        } else {
            $cloud_data = (new CloudServer())->getSiteAddonTokenCount(false);
            if (isset($cloud_data[$addon_name]) && $cloud_data[$addon_name]['surplus_count'] <= 0) {
                return $this->error("添加失败，应用token授权次数不足");
            }
            $token_res = (new CloudServer())->getSiteAddonToken($addon_name, $plaid);
            if ($token_res['code'] == -1) {
                return $this->error($token_res['msg']);
            } else {
                if ($token_res['code'] == -2) {
                    $token = 'local';
                } else {
                    if (isset($token_res['data']['token'])) {
                        $token = $token_res['data']['token'];
                    } else {
                        return $this->error("添加失败，token授权失败");
                    }
                }
                $platform_addon->aid = $aid;
                $platform_addon->plaid = $plaid;
                $platform_addon->addon_name = $addon_name;
                $platform_addon->token = $token;
                $platform_addon->save();
                Cache::delete("getSiteAddonTokenCount");
                return $this->success('添加成功');
            }
        }
    }

    /**
     * 添加应用小程序
     * @param $aid
     * @param $addon_name
     * @param $plaid
     */
    public function addPlatformAddonApp($aid, $addon_name, $plaid)
    {
        $platform = (new Platform())->where(['plaid' => $plaid])->find();
        // 已使用次数
        $platform_app_count = (new PlatformApp())->where(['aid' => $aid, 'addon_name' => $addon_name, 'plaid' => $plaid])->count();
        // 总次数
        $platform_app_user = (new PlatformAppUser())->where(['addon_name' => $addon_name, 'uid' => $platform['uid']])->find();

        if (!$platform_app_user || $platform_app_user['count'] < $platform_app_count) {
            return $this->error('当前应用可添加次数不足');
        }
        // 获取平台信息
        $cloud_data = (new CloudServer())->getSiteAddonTokenCount(false);
        if (isset($cloud_data[$addon_name]) && $cloud_data[$addon_name]['surplus_count'] <= 0) {
            return $this->error("添加失败，应用token授权次数不足");
        }
        $token_res = (new CloudServer())->getSiteAddonToken($addon_name, $plaid);
        // 判断小程序次数
        if ($token_res['code'] == -1) {
            // 应用无法添加
            return $this->error($token_res['msg']);
        } else {
            if ($token_res['code'] == -2) {
                // 本地应用
                $token = 'local';
            } else {
                // 线上应用
                if (isset($token_res['data']['token'])) {
                    $token = $token_res['data']['token'];
                } else {
                    return $this->error("添加失败，token授权失败");
                }
            }
            $app_data = array(
                'uid'        => $platform['uid'],
                'aid'        => $aid,
                'plaid'      => $plaid,
                'addon_name' => $addon_name,
                'token'      => $token
            );
            (new PlatformApp())->save($app_data);
            Cache::delete("getSiteAddonTokenCount");
            return $this->success('添加成功');
        }
    }

    public function getPlatformAddonForm()
    {
        $id = input("id", 0);
        $action = "/adminapi/platform/addon/save";
        $platform = (new Platform())->where(['plaid' => get_plaid()])->find();
        if (!$platform) {
            return $this->error('平台不存在');
        }
        if (!$id) {
            $id = $this->model->where(['plaid' => get_plaid(), 'addon_name' => get_addon()])->value('id');
        }
        $rule = array();
        $form = Form::createForm($action)->setMethod("POST");
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        $col = Form::col()->span(11)->offset(1)->pull(1);
        $rule[] = Form::hidden('id', $row->id);
        $rule[] = Form::switches('index', '首页显示', strval($row->index))->col($col)->effect(['help' => '显示到客户端首页']);
        $rule[] = Form::switches('menu', '菜单显示', strval($row->menu))->col($col)->effect(['help' => '显示到平台左侧列表页']);
        if (input('is_admin', 0)) {
            $rule[] = Form::input('token', "应用Token", $row['token'] ?? '')->effect(['help' => '平台下的应用Token，请勿随意修改，可能会导致应用部分云端功能无法使用']);
        }
        if ($platform['type'] == 3) {
            //企业微信
            $options = (new WeworkApps())->getFormOptions(get_plaid());
            $rule[] = Form::select('app_id', '自建应用', $row['config']['app_id'] ?? '')
                ->options($options)
                ->effect(['help' => "设置当前模块默认调用的自建应用，没有可以选无"]);
        }
        $rule[] = Form::input('sort', '排序', $row->sort);

        $addon_rules = event($row['addon_name'] . '_platform_addon_config', $row['config'])[0] ?? [];
        if (!$addon_rules) {
            $instance = get_addons_instance($row['addon_name']);
            if ($instance !== null && method_exists($instance, 'platform_addon_config')) {
                $addon_rules = $instance->platform_addon_config($row['config']);
            }
        }
        if (is_array($addon_rules)) {
            foreach ($addon_rules as $key => $value) {
                if ($value instanceof FormComponent) {
                    $rule[] = $value;
                } elseif ($value instanceof CustomComponent) {
                    $rule[] = (new CustomComponent('elCol'))->appendChild($value)->props(['style' => 'margin-bottom:22px']);
                }
            }
        }
        $form->setTitle("平台应用配置")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    public function save($formData = [])
    {
        $id = $formData['id'];
        $res = $this->model->where(['id' => $id])->find();
        if ($res) {
            $res->index = $formData['index'];
            $res->menu = $formData['menu'];
            $res->sort = $formData['sort'];
            if (isset($formData['token'])) {
                $res->token = $formData['token'];
            }
            $res->config = $formData;
            $res->save();
            return $this->success("修改成功");
        } else {
            return $this->error('修改失败，未找到对应应用');
        }
    }
}
